package com.lostandfound.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.lostandfound.entity.User;

/**
 * Servlet Filter implementation class LoginFilter
 */
public class LoginFilter implements Filter {

    /**
     * Default constructor. 
     */
    public LoginFilter() {}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession();
        String url=request.getServletPath();
        String contextPath=request.getContextPath();
        
        System.out.println("上下文路径：："+contextPath);
        //获取请求路径
        System.out.println("request'path="+url);
         
        /*String extension=url.substring(url.lastIndexOf(".")+1);
        System.out.println("当前请求的url的后缀名是什么-》："+extension);
        if (extension.equals("css") || extension.equals("js")|| extension.equals("xml")|| extension.equals("properties") || extension.equals("action") || extension.equals("do")){
            System.out.println("css,js,xml这些不是用户能访问的文件，抱歉。");
        }else{
            //下面是用户能访问的页面链接。不登陆都不能访问都不能访问。
            if(session.getAttribute("user")==null){
                if(url.equals("/login.html")){
                    arg2.doFilter(arg0, arg1);
                }else{
                    response.sendRedirect(contextPath+"/login.html");
                }
            }else{
                arg2.doFilter(arg0, arg1);
            }
        }*/
        
        if(url.equals("")) url+="/";  //&&url.endsWith(".action")
        if((url.startsWith("/")&&url.endsWith(".action")&&
        		!url.startsWith("/login") && !url.startsWith("/isUserExist") && !url.startsWith("/register"))){//若访问后台资源 过滤到login
        	User user=(User)session.getAttribute("loginUser");
             if(user==null){//转入管理员登陆页面 
                  response.sendRedirect(contextPath+"/login.html");
                  return;
             }
        }
        chain.doFilter(req, res);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {}

}
